package com.zx.account.controller;

import cn.hutool.core.date.DateUtil;
import com.zx.account.controller.vo.AccountVo;
import com.zx.account.entity.User;
import com.zx.account.service.ATypeService;
import com.zx.account.service.AccountService;
import com.zx.util.Constants;
import com.zx.util.SessionDataUtil;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import javax.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.DateTimeFormat.ISO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;


/**
 * @version v1.0
 * @Project: managing-self
 * @Title: AccountController
 * @Description: 消费查询
 * @author: zhangxue
 * @date: 2019年10月4日下午10:15:35
 * @company: 未知
 * @Copyright: Copyright (c) 2015
 */
@Slf4j
@Controller
@RequestMapping("/account")
public class AccountQueryController {

    @Autowired
    private AccountService accountService;

    @Autowired
    private ATypeService aTypeService;

    /**
     * 计算集合里面的消费总额
     *
     * @param li
     * @return
     */
    public static BigDecimal getSum(List<AccountVo> li) {
        Optional<BigDecimal> reduce = li.stream()
                .map(AccountVo::getPrice)
                .reduce(BigDecimal::add);
        return reduce.orElse(BigDecimal.ZERO);
    }

    /**
     * 计算一共是多少天
     *
     * @param li
     * @return
     */
    public static long getDays(List<AccountVo> li) {
        long count = li.stream()
                .map(x -> x.getConsumeDate().getTime())
                .distinct()//去重
                .count();// 统计数量
        return count;
    }

    /**
     * 消费记录查询页面
     *
     * @return
     */
    @RequestMapping("/searchView")
    public ModelAndView searchView(ModelAndView m) {
        Calendar today = Calendar.getInstance();
        Date beginDate = DateUtil.beginOfMonth(today).getTime();
        Date endDate = DateUtil.endOfMonth(today).getTime();
        return this.search(m, beginDate, endDate, 0, 0);
    }

    /**
     * @param m
     * @param beginDate 【可选】开始时间
     * @param endDate 【可选】结束时间
     * @param type 【可选】类型
     * @return
     * @Title: 消费记录查询
     * @date: 2019年10月5日下午5:45:35
     * @author: zhangxue
     */
    @PostMapping("/search")
    public ModelAndView search(ModelAndView m,
            @DateTimeFormat(iso = ISO.DATE) Date beginDate,
            @DateTimeFormat(iso = ISO.DATE) Date endDate,
            Integer type,
            Integer typeDetail
    ) {
        User user = SessionDataUtil.getUserInfo();
        // 查询数据
        try {
            List<AccountVo> queryData = this.accountService.getAccount(beginDate, endDate, type, typeDetail,
                    user.getId());
            // 计算总的消费金额
            BigDecimal sum = getSum(queryData);
            // 计算总的天数
            long days = getDays(queryData);
            // 平均值每日消费
            String avg = days == 0 ? "-/-" : String.format("%.1f", 1.0 * sum.intValue() / days);

            m.addObject("beginDate", DateUtil.format(beginDate, Constants.DATE_FORMAT_4));
            m.addObject("endDate", DateUtil.format(endDate, Constants.DATE_FORMAT_4));
            m.addObject("accounts", queryData);
            m.addObject("sum", sum);
            m.addObject("days", days);
            m.addObject("avg", avg);
            m.addObject("queryType", type);
            m.addObject("queryTypeDetail", typeDetail);
            m.addObject("types", this.aTypeService.getByUserId(user.getId()));
        } catch (Exception e) {
            log.error("消费记录查询页面出现异常", e);
            m.addObject("msg", "消费记录查询页面出现异常");
        }
        m.setViewName("account/searchView");
        return m;
    }

    /**
     * @param id
     * @return
     * @Title: 删除一条消费记录
     * @date: 2019年10月5日下午5:47:09
     * @author: zhangxue
     */
    @RequestMapping("/delete")
    public ModelAndView delete(ModelAndView m, HttpSession session, Integer id) {
        try {
            this.accountService.delete(id);
        } catch (Exception e) {
            log.error("消费记录删除查询页面出现异常", e);
            m.addObject("msg", "消费记录删除查询页面出现异常");
        }
        // 跳转回查询页面
        return this.searchView(m);
    }
}
